package net.lulihu.pangolin.headless.client.config;

import lombok.Getter;
import lombok.NoArgsConstructor;
import net.lulihu.pangolin.headless.client.kit.PenetrateConfigKit;
import net.lulihu.pangolin.headless.common.container.annotation.Component;
import net.lulihu.pangolin.headless.common.container.templet.Initialization;
import net.lulihu.pangolin.headless.common.model.Penetrate;
import net.lulihu.pangolin.headless.common.properties.ConfigProperties;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 启动配置
 */
@Getter
@NoArgsConstructor
@Component
public class StartupConfig implements Initialization {

    /**
     * 系统版本号
     */
    private String version;

    /**
     * 地址
     */
    private String host;

    /**
     * 端口
     */
    private Integer port;

    /**
     * 认证秘钥
     */
    private String secret;

    /**
     * 穿透地址
     */
    private List<Penetrate> penetrates;


    @Override
    public void after() {
        ConfigProperties startupConfig = ConfigProperties.getDefault();

        version = startupConfig.getStringValue("version");
        host = startupConfig.getStringValue("host");
        port = startupConfig.getIntValue("port");
        secret = startupConfig.getStringValue("secret");

        String penetrateStr = startupConfig.getStringValue("penetrate");

        if (penetrateStr == null || penetrateStr.length() == 0) {
            throw new RuntimeException("未设置穿透地址");
        }

        // 穿透映射 可能为空
        Map<String, String> penetrateMap = PenetrateConfigKit.readToMap();

        penetrates = new ArrayList<>();
        try {
            String[] pen = penetrateStr.split(",");
            for (String str : pen) {
                Penetrate penetrate = new Penetrate();
                penetrate.setAddress(str);
                penetrate.setMappingId(penetrateMap.get(str));
                penetrates.add(penetrate);
            }
        } catch (Exception e) {
            throw new RuntimeException("穿透地址设置错误，无法解析:" + penetrateStr);
        }
    }
}
